import React, { useState, useEffect, useRef } from "react";
import { Table, Button, Modal, message, Switch } from "antd";
import axios from "axios";
import {
  DeleteOutlined,
  EditOutlined,
  ExclamationCircleOutlined,
} from "@ant-design/icons";
import {} from "antd";

import ShowAddUser from "../../../components/addUser";

export default function UserList() {
  const { confirm } = Modal;
  const [userList, setUserList] = useState([]);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [regionList, setRegionList] = useState([]);
  const [roleList, setRoleList] = useState([]);
  const addForm = useRef(null);
  const {
    role: { roleType },
    region,
  } = JSON.parse(localStorage.getItem("token"));
  // console.log(roleType);
  // 注意1：用户列表不能全部渲染出来 需要根据当前登陆人的roleType(1,2,3)过滤出比起权限低的人
  // 如区域管理员(roleType=2)不可能看到超级管理员(roleType=1)出现在其用户列表中
  useEffect(() => {
    axios.get("http://localhost:5000/users?_expand=role").then((res) => {
      const list = res.data;
      // console.log(list);
      setUserList(list.filter((item) => item.role.roleType > roleType));
    });
  }, [roleType]);
  useEffect(() => {
    axios.get("http://localhost:5000/regions").then((res) => {
      const list = res.data;
      setRegionList(list);
    });
  }, []);
  useEffect(() => {
    axios.get("http://localhost:5000/roles").then((res) => {
      // console.log(res.data);
      const list = res.data;
      setRoleList(list);
    });
  }, []);
  const columns = [
    {
      title: "区域",
      dataIndex: "region",
      render: (id) => {
        return <b>{id}</b>;
      },
    },
    {
      title: "角色名称",
      dataIndex: "role",
      render: (role) => {
        return role.roleName;
      },
    },
    {
      title: "用户名称",
      dataIndex: "username",
    },
    {
      title: "角色状态",
      dataIndex: "roleState",
      //可接受两个参数，第一个参数是当前子项，第二个参数是当前项
      render: (roleState, item) => {
        return (
          <Switch checked={item.roleState} disabled={item.default}></Switch>
        );
      },
    },
    {
      title: "操作",
      render: (item) => {
        return (
          <div>
            <Button
              type="danger"
              shape="circle"
              icon={<DeleteOutlined />}
              disabled={item.default}
              onClick={() => showConfirm(item)}
            />
            &nbsp;
            <Button
              type="primary"
              shape="circle"
              icon={<EditOutlined />}
              disabled={item.default}
            />
          </div>
        );
      },
    },
  ];
  const showConfirm = (item) => {
    confirm({
      title: "确认删除该用户吗？",
      icon: <ExclamationCircleOutlined />,
      async onOk() {
        try {
          setUserList(userList.filter((data) => data.id !== item.id));
          await axios.delete(`http://localhost:5000/users/${item.id}`);
          message.success("删除成功");
        } catch (error) {
          message.error("删除失败");
        }
      },
      onCancel() {
        message.warning("取消删除");
      },
    });
  };
  const addUser = () => {
    // console.log(addForm); //注意其输出结果  会得到表单的各种方法
    addForm.current
      .validateFields()
      .then((value) => {
        // console.log(value);value可以获得表单中的值
        // post到后端，生成id,再设置userList
        axios
          .post("http://localhost:5000/users", {
            ...value,
            roleState: true,
            default: false,
          })
          .then((res) => {
            // console.log(res.data); id会自动生成
            setUserList([
              ...userList,
              {
                ...res.data,
                role: roleList.filter((item) => item.id === value.roleId)[0],
              },
            ]);
            setIsModalVisible(false);
            addForm.current.resetFields();
            message.success("添加成功");
          })
          .catch(() => {
            message.error("添加失败");
          });
      })
      .catch((info) => {
        message.error("输入格式不正确");
      });
  };
  return (
    <div>
      <Button type="primary" onClick={() => setIsModalVisible(true)}>
        新增用户
      </Button>
      <Table
        dataSource={userList}
        columns={columns}
        // rowKey设置key值
        rowKey={(item) => item.id}
        pagination={{ pageSize: 5 }}
      ></Table>
      <Modal
        visible={isModalVisible}
        title="增加用户"
        okText="确定"
        cancelText="取消"
        onCancel={() => setIsModalVisible(false)}
        onOk={() => addUser()}
      >
        <ShowAddUser
          roleList={roleList}
          regionList={regionList}
          region={region}
          roleType={roleType}
          ref={addForm}
        ></ShowAddUser>
      </Modal>
    </div>
  );
}
